package com.wlgc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wlgc.dao.UserDao;
import com.wlgc.entity.RestBean;
import com.wlgc.entity.User;
import com.wlgc.service.RegisterService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
@Service
public class RegisterServiceImpl implements RegisterService {
    @Resource
    StringRedisTemplate template;
    @Resource
    UserDao dao;
    @Override
    public RestBean register(int id, String username, String password,String email) {
        User user=dao.selectById(id);
        if (user==null)
        {
            return new RestBean(500,"您输入的学号不存在!");
        }
        if(!user.getEmail().equals(email))
            return new RestBean<>(500,"注册失败邮箱与学号不匹配！");
        //如果账户已注册，直接返回已经注册
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername,username);
        User user1 = dao.selectOne(wrapper);
        if (!ObjectUtils.isEmpty(user1))
        return new RestBean<>(500,"该账号名已存在");
        //设置账号密码
        BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
        user.setUsername(username);
        user.setPassword(encoder.encode(password));
        int update = dao.updateById(user);
             template.delete(email+":VerifyCode:");
           return new RestBean(200,"注册成功");
    }
}
